package com.dlwx.firefighting.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dlwx.firefighting.MainActivity;
import com.dlwx.firefighting.R;
import com.dlwx.firefighting.activity.GoodsDetailsActivity;
import com.dlwx.firefighting.activity.SearchActivity;
import com.dlwx.firefighting.adapter.HomeFragGridAdapter;
import com.dlwx.firefighting.adapter.HomePageAdapter;
import com.dlwx.firefighting.bean.CategoryBean;
import com.dlwx.firefighting.bean.GoodsBean;
import com.dlwx.firefighting.config.Constant;
import com.dlwx.firefighting.utils.DialogUtils;
import com.dlwx.firefighting.utils.ToastUtils;
import com.dlwx.firefighting.utils.glide.GlideImageLoaderForBanner;
import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.view.CommonHeader;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 商城fragment
 */
public class StoreFragment extends Fragment {

    @BindView(R.id.store_recyclerview)
    LRecyclerView storeRecyclerview;
    Unbinder unbinder;
    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.title_right_one_btn)
    ImageView titleRightOneBtn;
    private HomePageAdapter homePageAdapter;
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private List<GoodsBean> datas = new ArrayList<>();

    private int[] images = {0, 0, 0, 0};
    private String[] text = {"全部商品", "养生茶叶", "健康食品", "养生茶叶"};
    private HomeFragGridAdapter gridAdapter;
    Banner banner;
    CommonHeader header;
    private int page=1;
    private int requestNum=10;
    private int count=0;
    private TabLayout tabLayout;
    private boolean isRefresh=false;

    public StoreFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_store, container, false);
        unbinder = ButterKnife.bind(this, view);
        tvMiddleTitle.setText("商城");
        titleRightOneBtn.setVisibility(View.VISIBLE);
        initView();
        getDatas();
        getGoodsList(page);
        getBanner();
        return view;
    }

    private void getBanner() {
        OkGo.<String>post(Constant.BANNER)
                .tag(this)
             /*   （1、首页banner 2、商城banner3、学习中心banner）*/
                .params("position_id",2)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
//                        DealResult result=new DealResult();
//                        List<String> beans=result.deal(getActivity(),response,new TypeToken<BaseBean<String>>(){}.getType());
//                        initBanner(beans);
                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.toastForShort(getActivity(),getString(R.string.bad_net));
                    }
                });
    }

    private void getDatas() {
      /*  OkGo.<String>post(Constant.INDEX_TYPEGOOODS)
                .tag(this)
                .params("type",1)
                .params("num",6)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DealResult dealResult=new DealResult();
                        List<GoodsBean> beans=dealResult.deal(getActivity(),response,new TypeToken<BaseBean<GoodsBean>>(){}.getType());
                        initPagerViews(beans);
                    }
                    @Override
                    public void onError(Response<String> response) {
                        ToastUtils.toastForShort(getActivity(),getString(R.string.bad_net));
                        super.onError(response);
                    }
                });*/
        OkGo.<String>get(Constant.INDEX_CATEGORY)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
//                        DealResult dealResult=new DealResult();
//                        List<CategoryBean> beans=dealResult.deal(getActivity(),response,new TypeToken<BaseBean<CategoryBean>>(){}.getType());
//                        initTab(beans);
                    }
                    @Override
                    public void onError(Response<String> response) {
                        ToastUtils.toastForShort(getActivity(),getString(R.string.bad_net));
                        super.onError(response);
                    }
                });


    }
    private String catId="";
    private void getGoodsList(int page ){
        DialogUtils.showProgressDlg(getActivity(),"");
        OkGo.<String>post(Constant.INDEX_GOOODSLIST)
                .tag(this)
                .params("cat_id",catId)
                .params("page",page)
                .params("num",requestNum)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
//                        DealResult dealResult=new DealResult();
//                        List<GoodsBean> beans=dealResult.deal(getActivity(),response,new TypeToken<BaseBean<GoodsBean>>(){}.getType());
//                        if(isRefresh){
//                            homePageAdapter.clear();
//                        }
//                        homePageAdapter.addAll(beans);
//                        count=homePageAdapter.getItemCount();
//                        storeRecyclerview.refreshComplete(requestNum);
                    }
                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(getActivity(),getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    public void initView() {
        homePageAdapter = new HomePageAdapter(getActivity());
        storeRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        homePageAdapter.setDataList(datas);
        lRecyclerViewAdapter = new LRecyclerViewAdapter(homePageAdapter);
        storeRecyclerview.setAdapter(lRecyclerViewAdapter);
        storeRecyclerview.setPullRefreshEnabled(true);
        DividerDecoration divider = new DividerDecoration.Builder(getActivity())
                .setHeight(R.dimen.divider_height)
                .setPadding(R.dimen.divider_padding)
                .setColorResource(R.color.line_gray)
                .build();
        storeRecyclerview.addItemDecoration(divider);
        initHeader();
        storeRecyclerview.setPullRefreshEnabled(false);
        storeRecyclerview.setLoadMoreEnabled(true);
       /* //设置下拉刷新
        mainRecyclerview.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                adapter.clear();
                lRecyclerViewAdapter.notifyDataSetChanged();
            }
        });*/
        storeRecyclerview.refresh();
        //设置上拉加载更多
        storeRecyclerview.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if(count<(page*requestNum)){
                    ToastUtils.toastForShort(getActivity(),getString(R.string.no_more));
                    storeRecyclerview.setNoMore(true);
                }else{
                    isRefresh=false;
                    page++;
                    getGoodsList(page);

                }
            }
        });
        lRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                String id=homePageAdapter.getDataList().get(position).getGoods_id();
                Intent i=new Intent();
                i.putExtra("id",id);
                i.setClass(getActivity(), GoodsDetailsActivity.class);
                startActivity(i);
            }
        });

    }


    //创建header
    private void initHeader() {
        header = new CommonHeader(getActivity(), R.layout.groupon_index_header);
        banner = (Banner) header.findViewById(R.id.groupon_header_banner);
        ((TextView) header.findViewById(R.id.index_new_tv)).setVisibility(View.GONE);
        ((ViewPager) header.findViewById(R.id.index_new_vp)).setVisibility(View.GONE);
        tabLayout = (TabLayout) header.findViewById(R.id.tab_layout);
       /* viewPager = (ViewPager) header.findViewById(R.id.index_new_vp);*/
        RelativeLayout recomRl = (RelativeLayout) header.findViewById(R.id.main_recom_rl);
        RelativeLayout new_recomRl = (RelativeLayout) header.findViewById(R.id.main_newrecom_rl);
        recomRl.setVisibility(View.GONE);
        new_recomRl.setVisibility(View.GONE);


        lRecyclerViewAdapter.addHeaderView(header);

    }

    private void initBanner(List<String> banners){
        if(banners.isEmpty()){
            return;
        }
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
            }
        });
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setImageLoader(new GlideImageLoaderForBanner());
        banner.setImages(banners);
        banner.start();
    }

    private void initTab(final List<CategoryBean> beans){
        if(beans.isEmpty()||beans.size()<4){
            return;
        }
        tabLayout.addTab(tabLayout.newTab().setText("全部商品"));
        for(CategoryBean bean :beans){
            tabLayout.addTab(tabLayout.newTab().setText(bean.getCat_name()));
        }
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position=tab.getPosition();
               /* homePageAdapter.clear();
                lRecyclerViewAdapter.notifyDataSetChanged();*///
                isRefresh=true;
                page=1;
                if(position==0){
                    catId="";
                }else{
                    catId=beans.get(position-1).getCat_id();
                }
                getGoodsList(page);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }


    @OnClick({R.id.title_left_one_btn, R.id.title_right_one_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_one_btn:
                MainActivity mainActivity= (MainActivity) getActivity();
                mainActivity.onKeyDown(KeyEvent.KEYCODE_BACK, null);
                break;
            case R.id.title_right_one_btn:
                startActivity(new Intent(getActivity(), SearchActivity.class));
//                ToastUtils.toastForShort(getActivity(), "搜索");
                break;
        }
    }
}
